import React from 'react';
import {findDOMNode} from 'react-dom';
import classNames from 'classnames';
import Gesture from 'image-gesture';
import Image from '@components/image';
import './style.less';

class ImageView extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const view = findDOMNode(this.view);
    const container = findDOMNode(this.container);
    this.gesture = Gesture(view, container)
      .models(['pinch', 'pan', 'doubletap', 'tap', 'press'])
      .on('tap', this.props.onClick);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.src !== this.props.src) {
      this.events.reload();
    }
  }

  componentWillUnmount() {
    this.gesture && this.gesture.destroy();
  }

  setRef = (r) => {
    this.container = r;
  };

  render() {
    const {isLazy, width = 750, src, className} = this.props;
    const cls = classNames('image-view', className);
    return (
      <div className={cls} ref={r => this.view = r}>
        <div
          className='image-view-container'
          ref={r => this.view = r}
        >
          <Image src={src} width={width} isLazy={isLazy} setRef={this.setRef} />
        </div>
      </div>
    )
  }
}

export default ImageView;
